clear all
cd "I:\Workdata\706727\Build\Data"
use ChildhospRegOldMuniint


sort kom year age

/* first round */
gen cutoff=.

forvalues i=2/13 {
local j=`i'-1
local k=`i'+1

by kom year: replace cutoff=age[`i'] if childhosp[`j']-childhosp[`i']>0.15 & childhosp[`j']>=0.9 & childhosp[`i']-childhosp[`k']>-0.10 & mi(cutoff)  & !mi(childhosp[`j']) & !mi(childhosp[`i']) & !mi(childhosp[`k'])
by kom year: replace cutoff=age[`i'] if childhosp[`j']-childhosp[`i']>0.15 & childhosp[`j']==1 & childhosp[`k']<0.85 & mi(cutoff)  & !mi(childhosp[`j']) & !mi(childhosp[`i']) & !mi(childhosp[`k'])
by kom year: replace cutoff=age[`i'] if childhosp[`j']-childhosp[`i']>0.5 & childhosp[`j']>=0.95 & childhosp[`i']-childhosp[`k']>0.05  & mi(cutoff)  & !mi(childhosp[`j']) & !mi(childhosp[`i']) & !mi(childhosp[`k'])

}


/* second collapsed round */
gen year3=round((year-1)/3)*3
sort kom year3 age

by kom year3 age: egen mchildhosp=mean(childhosp)

by kom year3 age: gen dupli=_n

sort dupli kom year3 age

gen cutoff3=.

forvalues i=2/13 {
local j=`i'-1
local k=`i'+1

by dupli kom year3: replace cutoff3=age[`i'] if mchildhosp[`j']-mchildhosp[`i']>0.15 & mchildhosp[`j']>=0.85 & mchildhosp[`i']-mchildhosp[`k']>-0.10 & mi(cutoff3)  & !mi(mchildhosp[`j']) & !mi(mchildhosp[`i']) & !mi(mchildhosp[`k']) & dupli==1
by dupli kom year3: replace cutoff3=age[`i'] if mchildhosp[`j']-mchildhosp[`i']>0.15 & mchildhosp[`j']==1 & mchildhosp[`k']<0.85 & mi(cutoff3)  & !mi(mchildhosp[`j']) & !mi(mchildhosp[`i']) & !mi(mchildhosp[`k'])
by dupli kom year3: replace cutoff3=age[`i'] if mchildhosp[`j']-mchildhosp[`i']>0.5 & mchildhosp[`j']==1 & mchildhosp[`i']-mchildhosp[`k']>0.05  & mi(cutoff3)  & !mi(mchildhosp[`j']) & !mi(mchildhosp[`i']) & !mi(mchildhosp[`k'])

}

bysort kom year3: egen maxcutoff3=max(cutoff3)
replace cutoff3=maxcutoff3
drop maxcutoff3

keep kom year cutoff cutoff3

duplicates drop

sort kom year

replace cutoff=. if !inrange(cutoff,15,21)
replace cutoff3=. if !inrange(cutoff3,15,21)

forvalues i=2/13 {
by kom: replace cutoff=cutoff[_n-`i'] if mi(cutoff) & kom==kom[_n-`i']
by kom: replace cutoff=cutoff[_n+`i'] if mi(cutoff) & kom==kom[_n+`i']
replace cutoff=cutoff3 if mi(cutoff)
}

drop cutoff3


save ChildhospByKomYear, replace
